<template>
  <div class="table-container">
    <el-table
      :data="data"
      style="width: 100%"
      :expand-row-keys="expandedRows"
      row-key="id"
      @expand-change="$emit('expand-change', $event)"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <TableRow 
            :row="props.row" 
            :expandedRows="expandedRows"
            @toggle-row="$emit('toggle-row', $event)"
            @toggle-row-children="$emit('toggle-row-children', $event)"
          />
        </template>
      </el-table-column>
      
      <el-table-column
        label="用户 ID"
        prop="id"
        width="100"
      ></el-table-column>
      
      <el-table-column
        label="日期"
        prop="date"
        width="120"
      ></el-table-column>
      
      <el-table-column
        label="姓名"
        prop="name"
        width="120"
      ></el-table-column>
      
      <el-table-column
        label="地址"
        prop="address"
      ></el-table-column>
      
      <el-table-column
        label="操作"
        width="180"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            :type="isRowExpanded(scope.row) ? 'info' : 'primary'"
            @click="$emit('toggle-row', scope.row)"
          >
            {{ isRowExpanded(scope.row) ? '折叠' : '展开' }}
          </el-button>
          <el-button
            v-if="scope.row.children && scope.row.children.length > 0"
            size="mini"
            type="success"
            @click="$emit('toggle-row-children', scope.row)"
          >
            {{ isRowChildrenExpanded(scope.row) ? '折叠下层' : '展开下层' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import TableRow from './TableRow.vue'

export default {
  name: 'MultiLevelTable',
  components: {
    TableRow
  },
  props: {
    data: {
      type: Array,
      required: true
    },
    expandedRows: {
      type: Array,
      required: true
    }
  },
  methods: {
    isRowExpanded(row) {
      return this.expandedRows.includes(row.id)
    },
    
    isRowChildrenExpanded(row) {
      if (!row.children || row.children.length === 0) return false
      return row.children.every(child => this.isRowExpanded(child))
    }
  }
}
</script>

<style scoped>
.table-container {
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  overflow: hidden;
}
</style>